﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;
using System.Collections;
using System.IO;
using System.Web.UI.HtmlControls;

namespace TaobaoERP.Core.Common
{
    public class Function
    {
        public Function() { }

        #region 字符串处理
        /// <summary>
        /// 替换SQL
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string ReplaceSql(string msg)
        {
            if (msg != "" && msg != null)
            {
                msg = msg.Replace("'", "");
            }
            return msg;
        }

        public static string ReplaceXml(string msg)
        {
            if (msg != "" && msg != null)
            {
                msg = msg.Replace("&", "%26");
                msg = msg.Replace(">", "&gt;");
                msg = msg.Replace("<", "&lt;");
                msg = msg.Replace("\"", "&quot;");
                msg = msg.Replace("'", "&apos;");
            }
            return msg;
        }

        public static string ReplaceHtml(string text)
        {
            //text = System.Text.RegularExpressions.Regex.Replace(text, @"<[^>]*>", "",RegexOptions.Multiline);

            if (!string.IsNullOrEmpty(text))
                text = System.Text.RegularExpressions.Regex.Replace(text, @"<[^>]+>", "");
            return text;
        }
        public static string ReplaceSpam(string text)
        {
            Regex RegexFrom = new Regex("<FORM([^>]*)>", RegexOptions.IgnoreCase);
            text = RegexFrom.Replace(text, "");

            RegexFrom = new Regex("</FORM>", RegexOptions.IgnoreCase);
            text = RegexFrom.Replace(text, "");

            RegexFrom = new Regex("<PRE>", RegexOptions.IgnoreCase);
            text = RegexFrom.Replace(text, "");

            RegexFrom = new Regex("<script([^>]*)>(.*)</script>", RegexOptions.IgnoreCase);
            text = RegexFrom.Replace(text, "");


            return text;
        }

        public static string ReplaceTable(string text)
        {
            text = text.Replace("<table>", "");
            text = text.Replace("</table>", "");
            text = text.Replace("<tr>", "");
            text = text.Replace("<td>", "");
            text = text.Replace("</tr>", "");
            text = text.Replace("</td>", "");
            return text;
        }
        /// <summary> 截短字串的函数
        /// </summary>
        /// <param name="mText">要加工的字串</param>
        /// <param name="byteCount">长度</param>
        /// <returns>被加工过的字串</returns>
        public static string Left(string mText, int byteCount)
        {
            if (byteCount < 1) return mText;

            if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount)
            {
                return mText;
            }
            else
            {
                byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText);
                byte[] newBytes = new byte[byteCount];

                for (int i = 0; i < byteCount; i++)
                {
                    newBytes[i] = txtBytes[i];
                }

                return System.Text.Encoding.Default.GetString(newBytes);
            }
        }
        public static string LeftReplaceHtml(string mText, int byteCount)
        {
            return Left(ReplaceHtml(mText), byteCount);
        }
        /// <summary>将普通字符串格式化为HTML
        /// </summary>
        /// <param name="textStr">所要格式化的字符串</param>
        /// <param name="spotUrlEmail">是否自动识别"http://"或"https://"开头的URL和Email地址，识别出来的URL和Email将会自动加上超链接</param>
        /// <returns>格式化后的HTML代码</returns>
        public static string TextToHTML(string textStr, bool spotUrlEmail)
        {
            System.Text.StringBuilder html = new System.Text.StringBuilder(textStr);

            //html.Replace("&", "&amp;");   //2006-4-26修改。不对"&"进行转义了，不然无法处理好多个QueryString的URL
            html.Replace("  ", " &nbsp;");  //两个空格才转义，是为了较好处理带QueryString的URL后接空格的情况
            html.Replace("<", "&lt;");
            html.Replace(">", "&gt;");
            html.Replace("\"", "&quot;");
            html.Replace(@"\n", "<br />");  //IE中的换行为"\r\n"，FF中为"\n"
            html.Replace(@"\r", "<br />");

            if (spotUrlEmail)
            {
                int offset;

                Regex linkRegex = new Regex("(http(s)?://)([\\w-]+\\.)+[\\w-]+(/[\\w-./?&%=]*)?");
                MatchCollection linkMatches = linkRegex.Matches(html.ToString());
                offset = 0;
                foreach (Match match in linkMatches)
                {
                    string linkHead = string.Format("<a class=a_1 target=_brank href=\"{0}\">", match.Value);

                    html.Insert(match.Index + offset, linkHead);
                    offset += linkHead.Length;

                    html.Insert(match.Index + match.Length + offset, "</a>");
                    offset += 4;
                }

                Regex emailRegex = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
                MatchCollection emailMatches = emailRegex.Matches(html.ToString());
                offset = 0;
                foreach (Match match in emailMatches)
                {
                    string emailHead = string.Format("<a href=\"mailto:{0}\">", match.Value);

                    html.Insert(match.Index + offset, emailHead);
                    offset += emailHead.Length;

                    html.Insert(match.Index + match.Length + offset, "</a>");
                    offset += 4;
                }
            }

            textStr = html.ToString();
            Regex br = new Regex("(<br /><br />)+");
            textStr = br.Replace(textStr, "<br />");
            return textStr;
        }

        public static string TrimHtml(string content, int length)
        {
            Regex Content_regex = new Regex("<[^<>]+>?", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
            string input = "", temp = "";
            if (content.Length <= length)
                return content;
            //匹配出<>中的标签
            Match mx = Content_regex.Match(content, 0, content.Length);
            Stack tagStack = new Stack();
            int startIndex = 0;
            int maxlength = 0;
            //其实很简单，保证截取出来的段落有结束的html标签就可以了
            while (mx.Value != string.Empty)
            {
                temp = content.Substring(startIndex, mx.Index);
                //当然也要保证非显示字符数不要包括到要显示的字符数中。否则会严重影响简介的质量
                if (maxlength + temp.Length >= length)
                {
                    temp = temp.Substring(0, length - maxlength);
                    input = input + temp + "" + mx.Value;
                    break;
                }
                maxlength += temp.Length;
                input = input + temp + mx.Value;
                //一个先进后出队列，如果发现有结束，那么从堆栈中取出来
                if (mx.Value.EndsWith("/>"))
                {
                    if (tagStack.Count > 0)
                        tagStack.Pop();
                }
                else if (mx.Value.StartsWith("</"))
                {
                    if (tagStack.Count > 0)
                        tagStack.Pop();
                }
                else
                    tagStack.Push(mx.Value);

                int index = content.IndexOf(mx.Value);
                content = content.Remove(0, index);
                content = content.Remove(0, mx.Length);
                mx = Content_regex.Match(content, 0, content.Length);

            }
            if (maxlength == 0)
            {
                if (content.Length < length)
                    content = input + content;
                else
                    content = input + content.Substring(0, length) + "";
                return content;
            }
            //对先进后出队列中已经压入的开始标签填充结束标签
            while (tagStack.Count > 0)
            {
                string tag = tagStack.Pop().ToString();
                if (tag.IndexOf(' ') > 0)
                    tag = tag.Substring(0, tag.IndexOf(' ')).Replace("<", "");
                else
                    tag = tag.Replace("<", "").Replace(">", "");
                input = input + "</" + tag + ">";
            }
            input = Regex.Replace(input, "</br></br>", "", RegexOptions.IgnoreCase);
            return input;
        }

        /// <summary>处理获取字符串(String)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetStringSafeFromQueryString(string key)
        {
            string value = ReplaceSql(System.Web.HttpContext.Current.Request.QueryString[key]);
            return (value == null) ? string.Empty : value;
        }

        /// <summary>处理获取字符串(Int)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int GetInt32SafeFromQueryString(string key, int defaultValue)
        {
            string value = GetStringSafeFromQueryString(key);
            int i = defaultValue;
            try
            {
                i = int.Parse(value);
            }
            catch { }
            return i;
        }
        #endregion 

        /// <summary>获取实际路径
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static string GetMapPath(string strPath)
        {
            //if (HttpContext.Current != null)
            //{
                return HttpContext.Current.Server.MapPath(strPath);
            //}
            //return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
        }
        /// <summary>
        /// 添加样式表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="cssPath"></param>
        static public void AddStyleSheet(Page page, string cssPath)
        {
            HtmlLink link = new HtmlLink();
            link.Href = cssPath;
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";
            page.Header.Controls.Add(link);
        }
        /// <summary>Redirect实现弹出新窗口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="target"></param>
        /// <param name="windowFeatures"></param>
        public static void Redirect(string url, string target, string windowFeatures)
        {
            HttpContext context = HttpContext.Current;
            if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&  String.IsNullOrEmpty(windowFeatures))
            {
                context.Response.Redirect(url);
            }
            else
            {
                Page page = (Page)context.Handler;
                if (page == null)
                {
                    throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
                }
                url = page.ResolveClientUrl(url);
                string script;
                if (!String.IsNullOrEmpty(windowFeatures))
                {
                    script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
                    script = String.Format(script, url, target, windowFeatures);
                    page.ClientScript.RegisterStartupScript(typeof(Page), "Redirect", script, true);
                }
                else
                {
                    page.Form.Target = target;
                    context.Response.Redirect(url);
                }
                
            }
        }

        public static string GetConfig(string strConfig)
        {
            return System.Configuration.ConfigurationSettings.AppSettings[strConfig].ToString();
        }

        /// <summary>检查会话
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSession(string str)
        {
            if (System.Web.HttpContext.Current.Session[str] == null)
                return "";
            else
                return System.Web.HttpContext.Current.Session[str].ToString();
        }

        #region js处理
        public static void alert(string msg)
        {
            string scriptString = "alert('" + msg + "')";
            script(scriptString);
        }
        /// <summary>
        /// JS脚本处理
        /// </summary>
        /// <param name="msg"></param>
        
        public static void script(string msg)
        {
            string scriptString = "<script language=JavaScript> ";
            scriptString += msg + "<";
            scriptString += "/";
            scriptString += "script>";
            ((Page)HttpContext.Current.Handler).ClientScript.RegisterStartupScript(typeof(string), "", scriptString);
        }

        public static void ScriptBlock(string msg)
        {
            string scriptString = "<script language=JavaScript> ";
            scriptString += msg + "<";
            scriptString += "/";
            scriptString += "script>";
            ((Page)HttpContext.Current.Handler).ClientScript.RegisterClientScriptBlock(typeof(string), "", scriptString);
        }

        public static void alertBack(string msg)
        {
            string scriptString = "alert('" + msg + "');history.go(-1)";
            script(scriptString);
        }


        public static void location(string msg, string url)
        {
            string scriptString ="alert('" + msg + "');";
            scriptString += "location.href='" + url + "'";

            script(scriptString);
        }
        public static void location(string msg, string url,string tagert)
        {
            string scriptString = "alert('" + msg + "');";
            scriptString += tagert+".location.href='" + url + "'";

            script(scriptString);
        }
        #endregion 

        #region 获取ip
        /// <summary>
        /// 获取ip地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserIP()
        {
            string userIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            IPAddress myIP = IPAddress.Parse(userIP);
            return myIP.ToString();
        }
        /// <summary>
        /// 显示 IP 222.222.11.*
        /// </summary>
        /// <param name="IP">i</param>
        /// <returns></returns>

        public static string DisplayIP(string IP)
        {
            if (!string.IsNullOrEmpty(IP))
            {
                int end = IP.LastIndexOf(".");
                return IP.Substring(0, end) + ".*";
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 获取首字母或者汉字拼音首字母
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string HZtoSM(string path, string text)
        {
            try
            {
                string _FirstStr = text.Substring(0, 1);
                byte[] bytes;
                bytes = System.Text.Encoding.Default.GetBytes(_FirstStr);
                int Gbyte = Convert.ToInt16(bytes[0]);
                int Dbyte = Convert.ToInt16(bytes[1].ToString());
                int _fpos = (Gbyte - Convert.ToInt16('\x81')) * 191 + (Dbyte - 63);
                string GB2312SM = LoadFontLib(HttpContext.Current.Server.MapPath(@path) + "/GB2312SM.Lib").Trim();
                string msg = GB2312SM.Substring(_fpos, 1);
                return msg;
            }
            catch
            {
                string Msg = (text.Substring(0, 1)).ToUpper();
                return Msg;
            }
        }
        
        private static string LoadFontLib(string filename)
        {
            StreamReader _sr = new StreamReader(filename, System.Text.Encoding.Default);
            string text = "";
            while (_sr.Peek() > -1)
            {
                text += _sr.ReadLine();
            }
            return text;
        }
        #endregion

        public static int GetUserID()
        {
            if (System.Web.HttpContext.Current.Request.Cookies["UserID"] != null && System.Web.HttpContext.Current.Request.Cookies["UserID"].Value.Length > 0)
            {
                return Convert.ToInt32(System.Web.HttpContext.Current.Request.Cookies["UserID"].Value);
            }
            else
            {
                return 0;
            }

        }
    }
}
